import fs from 'fs';
import { fromMarkdown } from 'mdast-util-from-markdown';

const markdown = fs.readFileSync('./CHANGELOG.md', 'utf-8');
const ast = fromMarkdown(markdown);

const info = {
  version: '',
  time: '',
  fns: [],
};

let currentSection = null;

const versionTimeRegex = /^V(\d+\.\d+\.\d+) \((\d{4}\.\d+\.\d+)\)$/;

// 遍历AST节点
ast.children.forEach(node => {
  if (node.type === 'heading' && node.depth === 2) {
    const versionTimeMatch = versionTimeRegex.exec(node.children[0].value);
    if (versionTimeMatch) {
      info.version = versionTimeMatch[1];
      info.time = versionTimeMatch[2];
    }
  } else if (node.type === 'heading' && node.depth === 3) {
    currentSection = {
      title: node.children[0].value,
      lists: [],
    };
    info.fns.push(currentSection);
  } else if (node.type === 'list') {
    node.children.forEach(item => {
      const listItem = {
        title: '',
        desc: [],
        url: '',
        link: '',
        author: '',
      };

      item.children.forEach(part => {
        if (part.type === 'paragraph') {
          part.children.forEach(element => {
            if (element.type === 'text') {
              listItem.title += element.value;
            } else if (element.type === 'link') {
              listItem.author = element.children[0].value;
              listItem.link = element.url;
            } else if (element.type === 'image') {
              listItem.url = element.url;
            }
          });
        } else if (part.type === 'list') {
          listItem.desc = part.children.map(descItem =>
            descItem.children[0].children.map(text => text.value).join(' ')
          );
        }
      });

      currentSection.lists.push(listItem);
    });
  }
});

console.log(info);
fs.writeFileSync('./info444.json', JSON.stringify(info, null, 2));
